package com.iflytek.esb.controller;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.iflytek.esb.service.ConfigService;
import com.iflytek.esb.service.WorkflowService;
import com.iflytek.esb.vo.Service;
import com.opensymphony.workflow.loader.WorkflowDescriptor;

@Controller
@RequestMapping("/admin/service")
public class ServiceController {

	private static final Logger LOG = Logger.getLogger(ServiceController.class);

	private Date serverStartTime = new Date();
	
	@Autowired
	private ConfigService configService;
	
	@Autowired
	private WorkflowService workflowService;
	
	@RequestMapping("infomation")
	public ModelAndView infomation(HttpServletRequest request) {
		LOG.info("<open service infomation page>");
		
		Properties props = System.getProperties();
		long maxMemory = Runtime.getRuntime().maxMemory();
		long totalMemory = Runtime.getRuntime().totalMemory();
		
		ModelAndView mv = new ModelAndView("/service/infomation");
		
		mv.addObject("serverUrl", getServerUrl(request));
		mv.addObject("host", getHostName());
		mv.addObject("serverStartTime", getServerStartTime());
		
		mv.addObject("osName", props.get("os.name"));
		mv.addObject("osVersion", props.get("os.version"));
		mv.addObject("javaHome", props.get("java.home"));
		mv.addObject("javaRuntimeName", props.get("java.runtime.name"));
		mv.addObject("javaVersion", props.get("java.version"));
		mv.addObject("javaVendor", props.get("java.vendor"));
		mv.addObject("javaVmVersion", props.get("java.vm.version"));
		mv.addObject("maxMemory", maxMemory / 1024 / 1024);
		mv.addObject("totalMemory", totalMemory / 1024 / 1024);
		
		mv.addObject("applicationTitle", configService.getConfigValue("application.title"));
		
		mv.addObject("databaseType", configService.getJdbcProperty("database.type"));
		mv.addObject("databaseDriver", configService.getJdbcProperty("database.driver"));
		mv.addObject("databaseUrl", configService.getJdbcProperty("database.url"));
		mv.addObject("databaseUsername", configService.getJdbcProperty("database.username"));
		mv.addObject("databaseValidation", configService.getJdbcProperty("database.validation.query"));
		mv.addObject("databaseDialect", configService.getJdbcProperty("database.dialect"));
		
		return mv;
	}
	
	@RequestMapping("list")
	public ModelAndView list(HttpServletRequest request) {
		LOG.info("<open service list page>");
		
		String serverUrl = getServerUrl(request);
		ModelAndView mv = new ModelAndView("service/list");
		
		List<Service> services = new ArrayList<Service>();
		String[] names = workflowService.getWorkflowNames();
		for (String name : names) {
			Service s = new Service();
			s.setName(name);
			s.setStatus("check");
			s.setDescription("");
			s.setDisabled(false);
			s.setType("");
			s.setWsdl(serverUrl + "/services/" + name + "?wsdl");
			
			services.add(s);
		}
		
		mv.addObject("services", services);
		return mv;
	}
	
	@RequestMapping("detail")
	public ModelAndView detail(HttpServletRequest request, String serviceName) {
		
		String serverUrl = getServerUrl(request);
		ModelAndView mv = new ModelAndView("service/detail");
		
		Service s = new Service();
		s.setName(serviceName);
		s.setStatus("check");
		s.setDescription("发送人员数据到XX系统，包括人员基本信息和教育相关信息。XML格式，SOAP包封装");
		s.setDisabled(false);
		s.setType("");
		
		s.setWsdl(serverUrl + "/services/" + serviceName + "?wsdl");
		
		mv.addObject("service", s);
		return mv;
	}
	
	@RequestMapping("edit")
	public ModelAndView edit(String serviceName) {
		
		ModelAndView mv = new ModelAndView("service/edit");
		Service s = new Service();
		s.setName(serviceName);
		s.setStatus("check");
		s.setDescription("发送人员数据到XX系统，包括人员基本信息和教育相关信息。XML格式，SOAP包封装");
		s.setDisabled(false);
		s.setType("");
		
		WorkflowDescriptor wd = workflowService.getWorkflowDescriptor(serviceName);
		s.setXml(wd.asXML());
		
		mv.addObject("service", s);
		
		return mv;
	}

	@RequestMapping("update/service")
	@ResponseBody
	public Map<String, String> update(String serviceName, String description, String xml) {
		
		LOG.info("<update service workflow>");
		Map<String, String> r = new HashMap<String, String>();
		
		try {
			//workflowService.updateWorkflowDescriptor(serviceName, xml);
			r.put("result", "ok");
		}
		catch (Exception e) {
			r.put("result", "ng");
			r.put("message", e.getMessage());
		}
		
		return r;
	}
	
	private String getServerStartTime() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(serverStartTime);
	}

	private String getServerUrl(HttpServletRequest request) {
		String schema = request.getScheme();
		String server = request.getServerName();
		int port = request.getLocalPort();
		String context = request.getContextPath();

		String serverUrl = schema + "://" + server + (port == 80 ? "" : (":" + port)) + context;
		return serverUrl;
	}
	
	private String getHostName() {
		try {
			InetAddress inetAddress = InetAddress.getLocalHost();
			//String ip = inetAddress.getHostAddress();
			String name = inetAddress.getHostName();
			return name;
		}
		catch (UnknownHostException e) {
			return StringUtils.EMPTY;
		}
		
	}
}
